#!/usr/bin/env bash

# Copyright (C) 2018-19 Akhil Narang
# SPDX-License-Identifier: GPL-3.0-only

# Script defining various functions used in the scripts across this repository

# shellcheck disable=SC1090,SC1091
# SC1090: Can't follow non-constant source. Use a directive to specify location.

source ~/scripts/aliases

# Builds a package from the Arch User Repository
function aur() {
    git clone https://aur.archlinux.org/"${1}"
    cd "${1}" || return
    makepkg -si "${2}"
    cd - || return
    rm -rf "${1}"
}

# Repopicks a | delimited set of commits
function repopick_stuff() {
    export oldifs=$IFS
    export IFS="|"
    for f in ${REPOPICK_LIST}; do
        echo "Picking: $f"
        eval repopick "${f}" || return 1
    done
    export IFS=$oldifs
}

# Uploads a given file to transfer.sh
function transfer() {
    file="${1}"
    zipname=$(echo "${file}" | awk -F '/' '{print $NF}')
    destination="$2"
    url=$(curl -# -T "${file}" https://transfer.sh/"${destination}")
    printf '\n'
    echo -e "Download $zipname at $url"
}

# Repo sync with various flags I'm lazy to type each time
function syncc() {
    time repo sync --force-sync --no-clone-bundle --current-branch --no-tags "$@"
}

# Some git aliases for an easier workflow
function gitalias() {
    git config --global alias.s 'status'
    git config --global alias.p 'push'
    git config --global alias.pl 'pull'
    git config --global alias.f 'fetch'
    git config --global alias.r 'remote'
    git config --global alias.rv 'remote --verbose'
    git config --global alias.ru 'remote update'
    git config --global alias.rrm 'remote remove'
    git config --global alias.rsu 'remote set-url'
    git config --global alias.ra 'remote add'
    git config --global alias.rev 'revert'
    git config --global alias.re 'reset'
    git config --global alias.cp 'cherry-pick'
    git config --global alias.cpc 'cherry-pick --continue'
    git config --global alias.cpa 'cherry-pick --abort'
    git config --global alias.rh 'reset --hard'
    git config --global alias.rs 'reset --soft'
    git config --global alias.rb 'rebase'
    git config --global alias.rbi 'rebase --interactive'
    git config --global alias.rbc 'rebase --continue'
    git config --global alias.rba 'rebase --abort'
    git config --global alias.rbs 'rebase --skip'
    git config --global alias.d 'diff'
    git config --global alias.dc 'diff --cached'
    git config --global alias.b 'bisect'
    git config --global alias.c 'commit'
    git config --global alias.cs 'commit --signoff'
    git config --global alias.ca 'commit --amend'
    git config --global alias.cn 'commit --no-edit'
    git config --global alias.gerrit 'push gerrit HEAD:refs/for/pie'
    git config --global alias.add-change-id "!EDITOR='sed -i -re s/^pick/e/' sh -c 'git rebase -i \$1 && while test -f .git/rebase-merge/interactive; do git commit --amend --no-edit && git rebase --continue; done' -"
}

# Function to display uptime of a system. All credits to the original author.
function upinfo() {
    echo -ne "${green}$(hostname) ${red}uptime is ${cyan} \\t "
    uptime | awk /'up/ {print $3,$4,$5,$6,$7,$8,$9,$10,$11}'
}

# Function run on login to display some stuff and set my custom PS1
function onLogin() {
    # Colors
    green='\e[0;32m'
    cyan='\e[0;36m'
    red='\e[0;31m'
    lightgray='\e[0;37m'

    export GIT_PS1_SHOWDIRTYSTATE=1
    export GIT_PS1_SHOWSTASHSTATE=1
    export GIT_PS1_SHOWUNTRACKEDFILES=1
    export GIT_PS1_SHOWUPSTREAM=auto
    export GIT_PS1_SHOWCOLORHINTS=1
    unset PS1
    #PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
    if [[ -f "${HOME}/git-prompt.sh" ]]; then
        source ~/git-prompt.sh
        PS1='| \h (\w)$(__git_ps1 " {%s}") |-> '
    else
        PS1='| \h (\w) |-> '
    fi
    clear
    HOST=$(hostname)
    if [[ ${#HOST} -lt 14 ]]; then
        echo -e "${lightgray}"
        figlet -c "$(hostname)"
    fi
    echo ""
    echo -ne "${red}Today is:\\t\\t${cyan} $(date)"
    echo ""
    echo -e "${red}Kernel Information: \\t${cyan} $(uname -smr)"
    echo -ne "${cyan}"
    upinfo
    echo ""
    echo -e "Welcome to $(hostname), $(whoami)!"
    echo -e
    fortune
}

# Sends messages to Telegram to a specified chat via the desired bot
function sendTG() {
    local bot chat parse_mode msg
    bot="${BOT:-kronic}"
    chat="${1:-me}"
    parse_mode="${PARSE_MODE:-md}"
    shift
    msg=${*:?}
    case "${bot}" in
        "ts") BOT_API_KEY="$(cat ~/.tskey)" ;;
        "kronic") BOT_API_KEY="$(cat ~/.kronickey)" ;;
        "rr") BOT_API_KEY="$(cat ~/.rrkey)" ;;
        *)
            echo -e "Invalid bot, must be one of ts|kronic|rr!"
            return
            ;;
    esac

    case "${chat}" in
        "me") CHAT_ID="92027269" ;;
        "kernelberyllium") CHAT_ID="-1001297323361" ;;
        "aosip") CHAT_ID="-1001055786180" ;;
        *) CHAT_ID="${chat}" ;;
    esac

    case "${parse_mode}" in
        "md") parse_mode="Markdown" ;;
        "html") parse_mode="HTML" ;;
        *)
            echo -e "Invalid parse mode, must be one of Markdown|HTML!"
            return
            ;;
    esac
    curl -s "https://api.telegram.org/bot${BOT_API_KEY}/sendMessage" --data "text=${msg}&chat_id=${CHAT_ID}&parse_mode=${parse_mode}" 1> /dev/null
    echo
}

# Sends a message to my beryllium kernel chat
function sendKernelBeryllium() {
    sendTG kernelberyllium "${@}"
}

# Sends a message to AOSiP Testers group
function sendAOSiP() {
    if [[ ${QUIET:-no} == "no" ]]; then
        sendTG aosip "${@}"
    fi
}

# Sends me a message on telegram
function tgm() {
    sendTG me "${@}"
}

# Download a file given the Google Drive URL
function gdrivedl() {
    local CONFIRM FILE_ID URL
    URL="${1}"
    shift
    if [[ ${URL:?} =~ folders ]]; then
        FILE_ID="$(echo "${URL}" | sed -r -e 's/https.*folders\/(.*)/\1/' -e 's/(.*)\?usp=sharing/\1/')"
    else
        FILE_ID="$(echo "${URL:?}" | sed -r -e 's/(.*)&export.*/\1/' -e 's/https.*id=(.*)/\1/' -e 's/https.*\/d\/(.*)\/view/\1/')"
    fi
    CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$FILE_ID" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')
    aria2c --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$FILE_ID"
    rm -rf /tmp/cookies.txt
}

# Upload to GDrive
function gdriveul() {
    local FILE MD5 ZIP_SIZE GDRIVE_UPLOAD_URL GDRIVE_UPLOAD_ID UPLOAD_INFO PARENT
    FILE="${1}"
    [ -f "${FILE:?}" ] || {
        echo "Specified file doesn't exist"
        return
    }
    PARENT="${2}"
    if [[ -n ${PARENT} ]]; then
        PARENT="-p ${PARENT}"
    fi
    ZIP_SIZE="$(du -h "${FILE}" | awk '{print $1}')"
    MD5="$(md5sum "${FILE}" | awk '{print $1}')"
    while [ -z "${GDRIVE_UPLOAD_URL}" ]; do
        GDRIVE_UPLOAD_URL="$(eval gdrive upload --share "${FILE}" "${PARENT}" | awk '/https/ {print $7}')"
    done
    GDRIVE_UPLOAD_ID="$(echo "${GDRIVE_UPLOAD_URL}" | sed -r -e 's/(.*)&export.*/\1/' -e 's/https.*id=(.*)/\1/' -e 's/https.*\/d\/(.*)\/view/\1/')"
    UPLOAD_INFO="
File: [$(basename "${FILE}")](${GDRIVE_UPLOAD_URL})
Size: ${ZIP_SIZE}
MD5: \`${MD5}\`
GDrive ID: \`${GDRIVE_UPLOAD_ID}\`
"
    tgm "${UPLOAD_INFO}"
    echo "Get the file with ${GDRIVE_UPLOAD_ID}"
}
